package com.chenshu.transaction.dao;

import com.chenshu.transaction.model.BankAccount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2024-04-10
 * Time：10:23
 */
@Repository
public class BankAccountDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //账户合法性检查
    public BankAccount findAccountById(String id) {
        String sql = "select * from tb_bankAccount where id = ?";
        BankAccount bankAccount;
        try {
            bankAccount = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(BankAccount.class), id);
        } catch (Exception e) {
            //如果没查询到数据，就会抛运行异常，捕获异常，交给Service层处理。
            bankAccount = null;
        }
        return bankAccount;
    }

    //账户余额查询
    public Integer queryBalance(String id) {
        String sql = "select balance from tb_bankAccount where id= ? ";
        Map<String, Object> map = jdbcTemplate.queryForMap(sql, id);
        return (Integer) map.get("balance");
    }

    //转账操作
    public void updataAccountBalance(String id, int money) {
        String sql = "update tb_bankAccount set balance = balance + ? where id = ?";
        jdbcTemplate.update(sql, money, id);
    }

    public void updateAccountPassword(String id, String password) {
        String sql = "update tb_bankAccount set password = ? where id = ?";
        jdbcTemplate.update(sql, password, id);
    }
}
